import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.transaction.CuratorOp;
import org.apache.curator.framework.api.transaction.CuratorTransactionResult;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.util.List;

/**
 * @author create on 2021/7/9
 */
/**
 * 最后结果：
 * ResultStat : CREATEpath : /nodeTrans
 * ResultStat : CREATEpath : /nodeTrans/childNode
 * ResultStat : SET_DATApath : /nodeTrans
 * ResultStat : DELETEpath : /nodeTrans/childNode
 *
 * Zk支持事务操作，如果其中一个操作异常，则会抛出异常，所有操作都不会被执行。
 */
public class TransactionExamples {

    public static void main(String[] args) throws Exception {
        String connIp =  "127.0.0.1";
        //重试策略
        ExponentialBackoffRetry retryPolicy = new ExponentialBackoffRetry(1000, 3,Integer.MAX_VALUE);

        System.out.println("*********");
        CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient(connIp, retryPolicy);
        curatorFramework.start();

        //事务操作
        CuratorOp createNodeOp = curatorFramework.
                transactionOp().create().forPath("/nodeTrans", "data".getBytes());
        CuratorOp createChildNodeOp = curatorFramework.
                transactionOp().create().forPath("/nodeTrans/childNode", "data child".getBytes());
        CuratorOp changeNodeDataOp = curatorFramework.
                transactionOp().setData().forPath("/nodeTrans", "change data".getBytes());
        CuratorOp deleteNodeOp = curatorFramework.transactionOp().delete().forPath("/nodeTrans/childNode");

        List<CuratorTransactionResult> curatorTransactionResults = curatorFramework.transaction().
                forOperations(createNodeOp, createChildNodeOp, changeNodeDataOp, deleteNodeOp);
        for (CuratorTransactionResult curatorTransactionResult : curatorTransactionResults){
            System.out.println("ResultStat : " + curatorTransactionResult.getType() + "path : " + curatorTransactionResult.getForPath());
        }



    }
}
